package com.wulian.common.util;

import java.io.ByteArrayOutputStream;
import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;

@XmlRootElement
public class JAXBContextUtil {
	/**
	 * @author jiangjun
	 * @date 2018年8月31日 11:43:35
	 * @param object 传入要转xml的java bean
	 * @param enCodeStr 传入要转换的编码格式 GBK,utf-8
	 * @return String 如果转换成功为 未格式化成xml的字符串，否则为null
	 */
    public static String convertToXml(Object object,String enCodeStr) {
    	
        try {
        	JAXBContext context = JAXBContext.newInstance(object.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_ENCODING,enCodeStr);//xml 编码格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,false);//是否格式化生成的xml串
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);//是否省略xm头声明信息 ,
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
            //创建xml文件
            XMLStreamWriter xmlStreamWriter = xmlOutputFactory
                .createXMLStreamWriter(baos, (String) marshaller
                    .getProperty(Marshaller.JAXB_ENCODING));
            //头文件写入内容
            xmlStreamWriter.writeStartDocument(
                (String) marshaller.getProperty(Marshaller.JAXB_ENCODING),"1.0");
            marshaller.marshal(object, xmlStreamWriter);
            xmlStreamWriter.writeEndDocument();
            xmlStreamWriter.close();
            baos.close();
            return new String(baos.toString(enCodeStr));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;  	
    }
    /**
     * 
     * @param xml 需要转换成 bean 的xml字符串
     * @param Class<T> c 泛型转换之后的bean
     * @return
     */
    @SuppressWarnings("unchecked")
	public static <T> T converyToJavaBean(String xml, Class<T> c) {
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }
}
